<!--
 * @Author: chengjiang
 * @Date: 2025-04-11 16:31:29
 * @Description: 出入管理
-->
<script lang="ts" setup>
import type { FormSchemaGetter } from '#/adapter';
import type { VbenFormProps } from '#/adapter/form';
import type { VxeGridProps } from '#/adapter/vxe-table';

import { Page, useVbenModal } from '@vben/common-ui';
import { DictEnum } from '@vben/constants';

import { message, Popconfirm } from 'ant-design-vue';
import dayjs from 'dayjs';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  type Customer,
  customerDelete,
  customerList,
  // type CustomerListQuery,
  customerUpdate,
} from '#/api/inout/order';
import { getDictOptions } from '#/utils/dict';

import CustomerDetailAdd from './customer-detail-add.vue';
import { customerColumns } from './model';

const [CustomerModal, CustomerModalApi] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: CustomerDetailAdd,
});

const querySchema: FormSchemaGetter = () => [
  {
    component: 'Select',
    componentProps: {
      allowClear: true,
      options: getDictOptions(DictEnum.USER_COUSTOMER_LIST),
      placeholder: '请选择',
    },
    fieldName: 'name',
    label: '客户名称',
  },
  {
    component: 'Input',
    // defaultValue: '1',
    fieldName: 'id',
    label: '客户编号',
  },
  // {
  //   component: 'RangePicker',
  //   defaultValue: [dayjs().subtract(14, 'days'), dayjs()],
  //   fieldName: 'date',
  //   label: '日期',
  // },
];

export interface orderListParam {
  id?: number;
  name?: string;
  type: string;
  date: dayjs.Dayjs[];
}

function onSubmit(values: Record<string, any>) {
  message.success({
    content: `form values: ${JSON.stringify(values)}`,
  });
}

const formOptions: VbenFormProps = {
  // 默认展开
  collapsed: false,
  // fieldMappingTime: [['date', ['start', 'end']]],
  schema: querySchema(),
  // 控制表单是否显示折叠按钮
  showCollapseButton: false,
  // 是否在字段值改变时提交表单
  handleValuesChange: onSubmit,
  // 按下回车时是否提交表单
  // submitOnEnter: true,
  resetButtonOptions: {
    text: '重置',
    show: true,
  },
};

const gridOptions: VxeGridProps<Customer> = {
  checkboxConfig: {
    highlight: true,
    // labelField: 'id',
    checkMethod: ({ row }) => row.id !== 0,
  },
  columns: customerColumns,
  exportConfig: {},
  height: 'auto',
  keepSource: true,
  pagerConfig: {
    pageSize: 10,
  },
  proxyConfig: {
    autoLoad: true,
    response: {
      result: 'data',
      total: 'count',
      // list: '',
    },
    showActiveMsg: true,
    showResponseMsg: true,
    ajax: {
      query: async ({ page }, formValues) => {
        return await customerList({
          pageNo: page.currentPage,
          pageSize: page.pageSize,
          // name: formValues.name,
          // id: formValues.id,
          ...formValues,
        });
        // return {
        //   count: 100,
        //   data: [
        //     {
        //       id: 2,
        //       orderNo: '1234',
        //       processTime: '2023-04-11 16:31:29',
        //       customerName: 'chengjiang',
        //       remark: '123',
        //     },
        //   ],
        // };
      },
    },
  },
  rowConfig: {
    isHover: true,
    keyField: 'id',
  },
  editConfig: {
    mode: 'row',
    trigger: 'dblclick',
  },
  toolbarConfig: {
    custom: true,
    export: false,
    refresh: true,
    resizable: true,
    // search: true,
    zoom: true,
  },
};

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});

function handleDelete(row: Customer) {
  customerDelete(row.id)
    .then(() => {
      message.success(`删除成功`);
      gridApi.query();
    })
    .catch(() => {
      message.error(`删除用户 ${row.name} 失败`);
    });
}

function hasEditStatus(row: Customer) {
  return gridApi.grid?.isEditByRow(row);
}

function editRowEvent(row: Customer) {
  gridApi.grid?.setEditRow(row);
}

async function saveRowEvent(row: Customer) {
  await gridApi.grid?.clearEdit();

  gridApi.setLoading(true);
  setTimeout(() => {
    // 修改data里id为row.id的数据
    gridApi.setLoading(false);
    customerUpdate(row.id, row)
      .then(() => {
        gridApi.query();
        message.success({
          content: `保存成功！`,
        });
      })
      .catch(() => {
        message.error(`编辑用户 ${row.name} 失败`);
      });
  }, 600);
}
const cancelRowEvent = (_row: Customer) => {
  gridApi.grid?.clearEdit();
};

function openCustomerModal() {
  CustomerModalApi.open();
}
</script>

<template>
  <Page auto-content-height>
    <CustomerModal />
    <Grid>
      <!-- <template #toolbar-actions>
        <span class="pl-[7px] text-[16px]">列表</span>
      </template> -->
      <template #toolbar-tools>
        <p class="mr-3 text-xs text-gray-300">双击可快速编辑</p>
        <a-button type="primary" @click="openCustomerModal">新增</a-button>
      </template>
      <template #action="{ row }">
        <template v-if="hasEditStatus(row)">
          <a-button type="link" @click="saveRowEvent(row)">保存</a-button>
          <a-button type="link" @click="cancelRowEvent(row)">取消</a-button>
        </template>
        <template v-else>
          <a-button type="link" @click="editRowEvent(row)">
            {{ $t('pages.common.edit') }}
          </a-button>
          <Popconfirm
            placement="left"
            title="确认删除？"
            @confirm="handleDelete(row)"
          >
            <!--  v-access:code="['system:role:remove']" -->
            <a-button danger size="small" type="link" @click.stop="">
              {{ $t('pages.common.delete') }}
            </a-button>
          </Popconfirm>
        </template>
      </template>
    </Grid>
  </Page>
</template>
